package com.iqiyi.pps.epg.web.timer;

import com.google.common.util.concurrent.*;
import com.iqiyi.pps.epg.core.model.carousel.CarouselBase;
import com.iqiyi.pps.epg.core.service.carousel.CarouselService;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: jinlin
 * Date: 15-7-9
 * Time: 下午5:44
 * To change this template use File | Settings | File Templates.
 */
public class FollowUpdateTrigger {
    private static Logger logger = LoggerFactory.getLogger(FollowUpdateTrigger.class);
    private static final ListeningExecutorService listeningExecutorService =  MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));
    @Autowired
    private CarouselService carouselService;

    public void task() {
        logger.info("[FollowUpdateTrigger] task start");
        List<CarouselBase> carouselToFollow = carouselService.getCarouselToFollow();
        long startTime = System.currentTimeMillis();
        for(CarouselBase carouselBase: carouselToFollow) {
            try{
                    updateFollowQipuId(carouselBase);
            }catch (Exception e){
                logger.error("更新跟播视频节目信息失败：carouselBase id:{}",carouselBase.getId(),e);
            }

//            if(carouselService.checkCopyRightExpire(carouselBase,3)){ //提前3天提醒
//                logger.info("版权到期提醒：carouselBase id:{}",carouselBase.getId());
//            }
        }
        long endTime = System.currentTimeMillis();
        logger.info("[FollowUpdateTrigger] task end ："+(endTime - startTime));
    }

    private void updateFollowQipuId(final CarouselBase carouselBase){
        ListenableFuture<Long> explosion = listeningExecutorService.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                long start =  System.currentTimeMillis();
                try{
                    carouselService.updateFollowQipuId(carouselBase);
                }catch (Exception e){
                    logger.error("更新跟播视频节目信息失败：carouselBase id:{}"
                            ,carouselBase.getId(),e);
                }
                logger.info("更新跟播视频节目信息. CarouselBase id:{},time costs:{}ms",carouselBase.getId(), (System.currentTimeMillis()-start));
                return carouselBase.getId();
            }
        });
        Futures.addCallback(explosion, new FutureCallback<Long>() {
            @Override
            public void onSuccess(Long result) {

            }

            @Override
            public void onFailure(Throwable t) {

            }
        });

    }
}
